package cn.hchaojie.camp.javafx.part1;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class Palette extends Application {

	@Override
	public void start(Stage stage) throws Exception {
		Scene scene = new Scene(createContents());
		
		stage.setScene(scene);
		stage.show();
	}
	
	// 在这里创建页面布局
	private Parent createContents() {
		VBox box = new VBox(10);
		box.setPadding(new Insets(10));
		box.setAlignment(Pos.CENTER);
		
		// 用来显示rgb值的标签
		Label label = new Label();
		box.getChildren().add(label);
		
		// 用一个圆的背景颜色来直观的反应颜色变化
		Circle circle = new Circle(30);
		box.getChildren().add(circle);
		
		// 红色调节器
		Slider redSlider = new Slider(0, 255, 128);
		redSlider.valueProperty().addListener((ov, curVal, newVal) -> {
			showColor(circle, label, newVal.doubleValue() / 255, 1 /* red */);
		});
		box.getChildren().add(redSlider);

		// 绿色
		Slider greenSlider = new Slider(0, 255, 127);
		greenSlider.valueProperty().addListener((ov, curVal, newVal) -> {
			showColor(circle, label, newVal.doubleValue() / 255, 2 /* green */);
		});
		box.getChildren().add(greenSlider);

		// 蓝色
		Slider blueSlider = new Slider(0, 255, 128);
		blueSlider.valueProperty().addListener((ov, curVal, newVal) -> {
			showColor(circle, label, newVal.doubleValue() / 255, 3 /* blue */);
		});
		box.getChildren().add(blueSlider);

		return box;
	}
	
	private static void showColor(Circle circle, Label label, double value, int type) {
		Color oldColor = (Color) circle.getFill();

		Color color = null;
		switch (type) {
		case 1:			// red
			color = new Color(value, oldColor.getGreen(), oldColor.getBlue(), 1);
			break;

		case 2:			// green
			color = new Color(oldColor.getRed(), value, oldColor.getBlue(), 1);
			break;

		case 3:			// blue
			color = new Color(oldColor.getRed(), oldColor.getGreen(), value, 1);
			break;
		}
		circle.setFill(color);

		label.setText(String.format("(%3.0f, %3.0f, %3.0f)", 
				color.getRed() * 255, color.getGreen() * 255, color.getBlue() * 255));
	}
	
	public static void main(String[] args) {
		launch(args);
	}
}